<template>
    <el-select
              v-model="selectValue"
              placeholder="请选择"
              autocomplete
              filterable
              remote
              ref="select"
              reserve-keyword
              :remote-method="remoteMethod"
              @change="onChange"
              :loading="loading"
              clearable
              automatic-dropdown
            >
              <el-option
                v-for="(item, index) in subProjectOptions"
                :key="index + item.code"
                :label="item.label"
                :value="item.code"
              >
              </el-option>
            </el-select>
</template>

<script>

import { getSubjectList } from '@/components/map';

let list = [];

export default {
    data() {
        return {
            subProjectOptions: [],
            loading: false,
            selectValue: null
        };
    },
    props: {
        value: {
            type: String, 
            value: null
        }
    },
    mounted() {
       this.remoteMethod();
       this.selectValue = this.value;
    },
    watch: {
        value(n, o) {
          this.selectValue = n;
        }
    },
    methods: {
        async remoteMethod(query) {
            if (!list.length) {
              this.loading = true;
              list = await getSubjectList();
              this.loading = false;
            }
            if (query) {
               this.subProjectOptions = list.filter(v => v.label.indexOf(query) !== -1);
            } else {
                this.subProjectOptions = list;
            }
        },
        onChange(value) {
            if (this.value !== value) {
               this.$emit('input', value);
            }
            const val = value ? list.find(v => v.code === value) : null;
            this.$emit('change', value, value && val ? val.label : null);
        },
        focus() {
            this.$refs['select'].focus();
        }
    }
}
</script>
<style lang="less">

</style>
